package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate template;

    //发送验证码
    @Override
    public void sendVerifyCode(String phone, String code) {

        String key = RedisKeys.VERIFY_CODE.join(phone);
        //参数1:key 参数2:验证码 参数3:有效时间 参数4:时间单位
        template.opsForValue().set(key,code,RedisKeys.VERIFY_CODE.getTime(),TimeUnit.SECONDS);
    }

    //获取验证码
    @Override
    public String getVerifyCode(String phone) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        return template.opsForValue().get(key);

    }

    @Override
    public String setToken(UserInfo userInfo) {
        //创建token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        String value = JSON.toJSONString(userInfo);
        //把token作为key userInfo作为value存入redis
        template.opsForValue().set(key,value,RedisKeys.USER_LOGIN_TOKEN.getTime(),TimeUnit.SECONDS);
        return token;
    }

    @Override
    public UserInfo getUserInfoByToken(String token) {
        if (!StringUtils.hasLength(token)){
            return null;
        }
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        if (template.hasKey(key)){
            //获取用户对象
            String str = template.opsForValue().get(key);
            //反向转换用户对象  json->UserInfo
            UserInfo userInfo = JSON.parseObject(str, UserInfo.class);

            //重置token时间
            template.expire(key,RedisKeys.USER_LOGIN_TOKEN.getTime(),TimeUnit.SECONDS );
            return userInfo;
        }

        return null;
    }
}
